/*
	The example use JDBC-ODBC bridge to connecto to a Orale database on Cheval.
	The program is tested and running on MS Windows NT with ODBC DSN is registered
	as "ChevalDB"
*/
import java.sql.* ;
import java.net.* ;
import java.io.* ;

public class AccessSPDatabase {
	
	public static void main(String args[]) {
//		DriverManager.setLogStream() ;
		String url = "jdbc:odbc:ChevalDB";
		String usr = "CS440" ;
		String pwd = "student1" ;

		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		} catch(java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}

		try {
			Connection cnn = DriverManager.getConnection(url, usr, pwd) ;
			Statement stmt = cnn.createStatement() ;
			System.out.print("Enter the SQL SELECT String: ");
			byte ba[] = new byte[200];
			try { System.in.read( ba ); }
			catch(IOException e) {
				System.err.println("Error in reading SQL String: " + e.toString() ) ; 
			}
			
			ResultSet rs = stmt.executeQuery(new String(ba)) ;
			ResultSetMetaData rsmdata = rs.getMetaData() ;
			
			int lineLen = 0;
			for ( int i = 1; i <= rsmdata.getColumnCount(); i ++ ) {
				String s = rsmdata.getColumnName(i) ;
				int    len = s.length();
				System.out.print(s + spaces(rsmdata.getPrecision(i) + 5 -len) );
				lineLen = lineLen + rsmdata.getPrecision(i) + 5;
			}
			System.out.println();

			// Print underline as long as record length
			for (int i = 0; i < lineLen; i ++ ) System.out.print("="); System.out.println();
			while ( rs.next() ) {
				for ( int i = 1; i <= rsmdata.getColumnCount(); i ++) {
					String s = rs.getString(i) ;
					System.out.print(s + spaces(rsmdata.getPrecision(i) + 5 - s.length()) );
				}
				System.out.println();
			}
			for (int i = 0; i < lineLen; i ++ ) System.out.print("="); System.out.println();
			stmt.close();
			cnn.close();
		} catch( SQLException e ) { System.out.println(e.toString()) ; }
/*		
		try {
			System.in.read(); // prevent console window from going away
		} catch (java.io.IOException e) {}
*/
	}
	private static String spaces(int n) {
		String s = "" ;
		for( int i = 0 ; i < n; i ++ ) s = s + " ";
		return s; }
}